﻿using Max.PH4_2104A.Shopping.Domain;
using Max.PH4_2104A.Shopping.IRepository;
using Max.PH4_2104A.Shopping.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH4_2104A.Shopping.Service
{
    public class CategoryService : ICategoryService
    {
        ICategoryRepository _repository;
        IUnitOfWork _unitOfWork;
        /// <summary>
        /// 构造注入仓储接口
        /// </summary>
        /// <param name="repository"></param>
        public CategoryService(ICategoryRepository repository, IUnitOfWork unitOfWork)
        {
            _repository = repository;
            _unitOfWork = unitOfWork;
        }

        public IQueryable<CategoryModel> GetAll()
        {
            return _repository.GetAll();
        }

        public int Insert(CategoryModel model)
        {
            _repository.Insert(model);
            return _unitOfWork.SaveChanges();
            
        }

        public dynamic GetRecurseCategory()
        {
            var d = this.GetRecurseCategory(_repository.GetAll().ToList(), Guid.Empty.ToString());
            return d;
        }

        /*
         * 递归两个特点
         * 1、自己调用自己
         * 2、有结束条件
         * 
         * **/
        private List<dynamic> GetRecurseCategory(List<CategoryModel> list, string id)
        {
            List<dynamic> result = new(); //定义一个集合，用来保存查询的结果

            var data =list.Where(x=>x.ParentId.ToString().Equals(id));
            foreach (var item in data)
            {
               
                var d = GetRecurseCategory(list,item.Id.ToString());

                result.Add(new
                {
                    Id = item.Id,
                    Name = item.Name,
                    Children = d != null && d.Count > 0 ? d : null
                });
            }
            return result;
        }


        //private void _GetRecurseCategory(string id)
        //{
        //    var data = _repository.GetAll().Where(x => x.ParentId.ToString().Equals(id));
        //    foreach (var item in data)
        //    {
        //         GetRecurseCategory(item.Id.ToString());
        //    }
        //}
    }
}
